// 发布页面服务逻辑

import type { PublishForm, PublishResponse } from './types'

const API_BASE_URL = 'http://localhost:3000/api'

// 发布文章
export const publishArticle = async (form: PublishForm): Promise<PublishResponse> => {
  const token = localStorage.getItem('token')
  const res = await fetch(`${API_BASE_URL}/articles`, {
    method: 'POST',
    headers: {
      'Content-Type': 'application/json',
      Authorization: `Bearer ${token}`
    },
    body: JSON.stringify({
      title: form.title,
      content: form.content,
      excerpt: form.excerpt,
      category: form.category,
      tags: form.tags.join(','),
      coverImage: form.coverImage
    })
  })

  if (!res.ok) {
    const error = await res.json()
    throw new Error(error.message || '发布失败')
  }

  return await res.json()
}

// 上传封面图片
export const uploadCoverImage = async (file: File): Promise<string> => {
  const token = localStorage.getItem('token')
  const formData = new FormData()
  formData.append('cover', file)

  const res = await fetch(`${API_BASE_URL}/upload/cover`, {
    method: 'POST',
    headers: { Authorization: `Bearer ${token}` },
    body: formData
  })

  if (!res.ok) {
    throw new Error('封面图片上传失败')
  }

  const data = await res.json()
  return data.url
}

// 获取封面图片URL
export const getCoverUrl = (url?: string): string => {
  if (!url) return 'https://picsum.photos/800/400?random=default'
  if (/^https?:/.test(url)) return url
  return `${API_BASE_URL}${url}`
}

// 处理图片加载错误
export const onImgError = (e: Event): void => {
  const target = e.target as HTMLImageElement
  if (target) target.src = 'https://picsum.photos/800/400?random=default'
} 